const Controller = require('egg').Controller;
const fs = require('fs');
const path = require('path');
const PDFParser = require('pdf2json');
const ErrorUtil = require('../../class/error');
module.exports = app => {
  return class ResourceController extends Controller {
    async list() {
      const ctx = this.ctx;
      const query = ctx.query;
      if (query.folderId) {
        ctx.locals = {
          folder: await this.service.folder.selectById(+query.folderId),
          children: await this.service.folder.list(+query.folderId, query.name),
          files: await this.service.resource.list(+query.folderId, query.name, query.type),
        }
      } else {
        ctx.locals = {
          children: await this.service.folder.list(0, query.name),
          files: await this.service.resource.list(0, query.name, query.type),
        }
      }
      Object.assign(ctx.locals, {
        params: query
      })
      // ctx.body = ctx.locals;
      await ctx.render('admin/resource/list.html');
    }
    
    /**
     * @description 选择
     * @author xiezuobing[948466]<435321508@qq.com>
     */
    async select(){
      const ctx = this.ctx;
      const query = ctx.query;
      if (query.folderId) {
        ctx.locals = {
          folder: await this.service.folder.selectById(+query.folderId),
          children: await this.service.folder.list(+query.folderId, query.name),
          files: await this.service.resource.list(+query.folderId, query.name, query.type),
        }
      } else {
        ctx.locals = {
          children: await this.service.folder.list(0, query.name),
          files: await this.service.resource.list(0, query.name, query.type),
        }
      }
      Object.assign(ctx.locals, {
        params: query
      })
      // ctx.body = ctx.locals;
      await ctx.render('admin/resource/select.html');
    }


    /**
     * @description 文件详情
     * @author xiezuobing[948466]<435321508@qq.com>
     * @memberof ResourceController
     */
    async detail() {
      const ctx = this.ctx;
      if (ctx.query.fileId) {
        ctx.locals = {
          file: await this.service.resource.selectById(ctx.query.fileId),
          viewLogs: await this.service.operationLog.getPreList(
            app.config.operationType.target.RESOURCE,
            app.config.operationType.type.VIEW,
            ctx.query.fileId
          ),
          downloadLogs: await this.service.operationLog.getPreList(
            app.config.operationType.target.RESOURCE,
            app.config.operationType.type.DOWNLOAD,
            ctx.query.fileId
          ),
        }
      // ctx.body = ctx.locals;
      }
      await ctx.render('admin/resource/detail.html');
    }

    /**
     * @description 逻辑删除
     * @author xiezuobing[948466]<435321508@qq.com>
     * @memberof ResourceController
     */
    async clearJson() {
      const ctx = this.ctx;
      try {
        await this.service.resource.clear({
          id: ctx.query.fileId,
          delete_flag: 1
        });
        ctx.body = ErrorUtil.SUCCESS;
      } catch (e) {
        ctx.body = ErrorUtil.UNKOWN;
      }
    }

    /**
     * @description 编辑文件
     * @author xiezuobing[948466]<435321508@qq.com>
     * @memberof ResourceController
     */
    async editJson() {
      const ctx = this.ctx;
      try {
        await this.service.resource.update({
          id: ctx.query.fileId,
          name: ctx.query.name,
          modify_time: new Date()
        });
        ctx.body = ErrorUtil.SUCCESS;
      } catch (e) {
        ctx.body = ErrorUtil.UNKOWN;
        throw e;
      }
    } 
    
    /**
     * @description 查看文档
     * @author xiezuobing[948466]<435321508@qq.com>
     */
    async viewFile(){
      const ctx = this.ctx;
      const resource = await this.service.resource.selectById(this.ctx.query.resourceId);
      ctx.locals = {
        file: resource,
      }
      await ctx.render('front/resource/pdf_viewer.html');
    }

    /**
     * @description 
     * @author xiezuobing[948466]<435321508@qq.com>
     * @param {any} resourceId 
     */
    async parseFdp() {
      const ctx = this.ctx;
      const query = ctx.query;
      const resourceId = query.resourceId;
      try {
        const resource = await this.service.resource.selectById(resourceId);
        if (resource.type == 2 && resource.mime == "application/pdf") {
          let filePath = path.join(app.config.root, resource.url);
          let writePath = path.join(app.config.root, `public/json/${Date.now()}.json`);
          //pdf2json
          const pdfData = await pdfParserPromise(filePath);
          // ctx.body = JSON.parse(decodeURIComponent(JSON.stringify(pdfData.formImage.Pages)));
          ctx.body = pdfData.formImage.Pages;
        } else {
          ctx.body = ErrorUtil.FILETYPEERROR;
        }
      } catch (e) {
        ctx.body = ErrorUtil.UNKOWN;
        throw e;
      }
    }

  }
}

function pdfParserPromise(fileName, fromBuffer) {
  return new Promise(function(resolve, reject) {
    var pdfParser = new PDFParser();

    pdfParser.on("pdfParser_dataReady", function(evtData) {
      resolve(evtData);
    });

    pdfParser.on("pdfParser_dataError", function(evtData) {
      reject(new Error(evtData.data));
      console.log('mock read error1111');
    });

    var pdfFilePath = fileName;
    if (fromBuffer) {
      pdf = fs.readFileSync(pdfFilePath);
      pdfParser.parseBuffer(pdf);
    } else {
      pdfParser.loadPDF(pdfFilePath, 5);
    }
  });
}